package com.ly.mp.busicen.rule.field.validator.plugin;

import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.ly.mp.busicen.rule.field.validator.IValidData;
import com.ly.mp.busicen.rule.field.validator.IValidation;
import com.ly.mp.busicen.rule.field.validator.ValidatorBase;
import com.ly.mp.busicen.rule.flow.FlowUserMode;

@Component
public class FieldSpelValid extends ValidatorBase{

	@Override
	public boolean valid(IValidData validData, IValidation validation) {
		String param = validation.strParam();
		if (!StringUtils.isEmpty(param)) {
			return getDataFromContextSpel(validData.source(), param, Boolean.class);
		}
		return true;
	}

	@Override
	public String validName() {
		return "spel";
	}
	
	public static <T> T getDataFromContextSpel(Object context,String el,Class<T> clazz) {
		ExpressionParser parser = new SpelExpressionParser();
		EvaluationContext econtext=new StandardEvaluationContext();
		econtext.setVariable("data", context);
		econtext.setVariable("user", FlowUserMode.currentUser());
		Expression expression = parser.parseExpression(el);
		T data = expression.getValue(econtext,clazz);
		return data;
	}
}
